package com.fzb.ftp.start;

import com.fzb.ftp.FtpManager;
import com.fzb.ftp.FtpNIOClient;
import com.fzb.ftp.FtpUser;

public class FtpStart {

	public static void main(String[] args) {
		if(args==null || args.length==0){
			args="--host 203.195.167.55 --userName test --password K~wqYDZpTg2".split(" ");
		}
		if (hasParameter(args, "--help") || hasParameter(args, "-h")) {
			showUsage(null);
		}
		//
		String host = getParameter(args, "--host");
		String userName = getParameter(args, "--userName");
		String password = getParameter(args, "--password");
		String port = getParameter(args, "--port");
		String cmd = getParameter(args, "--cmd");
		FtpUser user = new FtpUser();
		user.setAddr(host);
		user.setPassword(password);
		user.setUserName(userName);
		if(port!=null){
			user.setPort(Integer.parseInt(port));
		}
		if(cmd!=null){
			new FtpManager().sendCmd(user,cmd.replace("*"," "));
		}
		else{
			new FtpNIOClient(null,user).connectServer();
		}
	}

	/**
	 * Return the value of the given parameter if set
	 *
	 * @param args
	 *            startup arguments
	 * @param name
	 *            parameter name
	 *
	 * @return the value of the given parameter if set or null
	 */
	private static String getParameter(final String args[], final String name) {
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals(name)) {
				if ((i + 1) < args.length) {
					return args[i + 1];
				} // end if

				break;
			} // end if
		} // end for

		return null;
	} // end getParameter()

	/**
	 * return true if the given parameter is on the command line
	 *
	 * @param args
	 *            startup arguments
	 * @param name
	 *            parameter name
	 *
	 * @return true if the given parameter is on the command line
	 */
	private static boolean hasParameter(final String args[], final String name) {
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals(name)) {
				return true;
			} // end if
		} // end for

		return false;
	} // end hasParameter()

	/**
	 * Show the usage of the tool
	 *
	 * @param message
	 *            An error message
	 */
	private static void showUsage(final String message) {
		if (message != null) {
			System.out.println(message);
		} // end if

		System.out
				.println("Usage :\n\tjava -jar simpleftpclient.jar "
						+ " --host 127.0.0.1 --userName test --password 123456  [cmd]");
		if (message != null) {
			System.exit(-2);
		} else {
			System.exit(0);
		}
	} // end showUsage()
}
